import axios from 'axios'
import { message as antdMessage } from 'ant-design-vue'

// 基础地址：优先使用环境变量，否则同源（配合 Vite 代理）
const BASE_URL = import.meta.env.VITE_API_BASE || ''

const http = axios.create({
  baseURL: BASE_URL,
  timeout: 300000,
  withCredentials: false
})

// 请求拦截：可在此统一附加 token、traceId 等
http.interceptors.request.use(
  (config) => {
    config.headers = config.headers || {}
    if (!config.headers['Content-Type']) {
      config.headers['Content-Type'] = 'application/json;charset=UTF-8'
    }
    // 调试信息
    console.log(`[HTTP Request] ${config.method?.toUpperCase()} ${config.url}`, config)
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截：统一处理后端返回结构与错误提示
http.interceptors.response.use(
  (response) => {
    const data = response.data
    // 调试信息
    console.log(`[HTTP Response] ${response.status} ${response.config.url}`, data)
    
    // 统一返回体：{ success, code, message, data }
    if (data && typeof data === 'object' && 'success' in data && 'code' in data) {
      if (data.success) return data.data
      const msg = data.message || `请求失败 (${data.code})`
      try { antdMessage.error(msg) } catch (_) {}
      return Promise.reject(Object.assign(new Error(msg), { response: { data } }))
    }
    // 非统一返回（如 @SkipWrap 的文本），原样返回
    return data
  },
  (error) => {
    // 详细的错误信息
    console.error('[HTTP Error]', error)
    if (error.code === 'ECONNREFUSED') {
      console.error('[Connection Refused] 请检查后端服务是否启动，端口是否正确')
    }
    if (error.code === 'ENOTFOUND') {
      console.error('[Host Not Found] 请检查IP地址是否正确')
    }
    
    const msg = error?.response?.data?.message || error?.message || '网络错误或服务器异常'
    // 尽量避免重复弹错
    try { antdMessage.error(msg) } catch (_) {}
    return Promise.reject(error)
  }
)

// 便捷方法
const get = (url, params, config = {}) => http.get(url, { params, ...config })
const post = (url, data, config = {}) => http.post(url, data, config)
const put = (url, data, config = {}) => http.put(url, data, config)
const del = (url, config = {}) => http.delete(url, config)

export { http, get, post, put, del }
export default http

